﻿using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;

namespace DimensionsHelper.LanguageService.Syntax;

public class DoubleLiteral : Literal<double>
{
    internal DoubleLiteral(SyntaxNode? parent) : base(SyntaxKinds.Double, 0d, parent)
    {
    }

    /// <summary>
    ///     默认的空浮点数常量
    /// </summary>
    public static DoubleLiteral Default { get; } = new(null);


    /// <summary>
    ///     判断浮点数常量是否是默认值
    /// </summary>
    /// <param name="literal"></param>
    /// <returns></returns>
    public static bool IsDefault(DoubleLiteral literal)
    {
        return ReferenceEquals(literal, Default);
    }
}


public static partial class NodeFactory
{
    public static DoubleLiteral CreateDoubleLiteral(SyntaxNode? parent, double value)
    {
        return new DoubleLiteral(parent) { Value = value };
    }


    public static DoubleLiteral CreateDoubleLiteral(SourceNode source)
    {
        Debug.Assert(source.IsNode(SyntaxKinds.Double));
        DoubleLiteral literal = CreateDoubleLiteral(null, source.TokenNumberValue);
        literal.UpdateFrom(source);
        return literal;
    }
}


public static partial class NodeConverter
{
    public static bool TryConvertNegativeDouble(Expression expression,
        [MaybeNullWhen(false)] out DoubleLiteral doubleLiteral)
    {
        doubleLiteral = null;

        if (expression.Is<UnaryExpression>(SyntaxKinds.UnaryExpression, out UnaryExpression? unary) &&
            unary.Operator.IsNode(SyntaxKinds.MinusToken) &&
            unary.Expression.Is<DoubleLiteral>(SyntaxKinds.Double, out DoubleLiteral? literal))
        {
            doubleLiteral = NodeFactory.CreateDoubleLiteral(null, -literal.Value);
            doubleLiteral.UpdateFrom(expression);
            return true;
        }

        return false;
    }
}